from django.shortcuts import render,HttpResponse,redirect,HttpResponsePermanentRedirect
from rest_framework.views import APIView
from rest_framework.response import Response
from captcha.image import ImageCaptcha
import jwt,redis,random,json,requests
import string,re,time
from zbj.my_redis import r
from zbj.models import *
from zbj.sms_code import sms_code
from zbj.my_jwt import jj
from zbj.urlis.tool import Get_resource
from qiniu import Auth
# 导包密码加密
from django.contrib.auth.hashers import make_password,check_password

# 生成图片验证码的接口
class Img_code(APIView):
    def get(self,request):
        uuid=request.query_params.get("uuid")
        img_code="".join(random.sample(string.digits+string.ascii_letters,4))
        cap=ImageCaptcha()
        img=cap.generate(img_code)
        r.set_str(uuid,img_code,120)
        return HttpResponse(img,content_type="image/png")

# 生成短信验证码
class Sms_code(APIView):
    def post(self,request):
        uuid = request.data.get("uuid")
        imgcode=request.data.get("imgcode")
        mobile=request.data.get("mobile")
        if not all([uuid,mobile,imgcode]):
            return Response({"code":400,'msg':'字段不完整'})
        if not re.findall(r"1[3-9]\w{9}$",mobile):
            return Response({"code":400,'msg':'手机号格式错误'})
        mob=r.get_str("code"+mobile)
        if mob:
            return Response({"code":400,'msg':'请勿重复操作'})
        res=r.get_str(uuid)
        if res:
            res=res.decode()
            if res.lower()!=imgcode.lower():
                return Response({"code":400,'msg':'图片验证码错误'})
            sms_code(mobile)
            r.del_str(uuid)
            return Response({"code":200,'msg':'发送成功，请注意查收'})
        else:
            return Response({"code":400,'msg':'图片验证码过期，请刷新重试'})

# 手机号登录
class mobile_Login(APIView):
    def post(self,request):
        smscode=request.data.get("smscode")
        mobile=request.data.get("mobile")
        if not all([smscode,mobile]):
            return Response({"code":400,'msg':'请输入完整的信息进行登录'})
        res=r.get_str(mobile)   #短信验证码解码
        if res:
            res=res.decode()
            if res!=smscode:
                return Response({"code":400,'msg':'手机号验证码错误，请重新输入'})
            try:
                r.del_str(mobile)
                user=User.objects.get(mobile=mobile)
                print("user>>>>>>>",user)
                token=jj.jwt_encode(data={"id":user.id,"mobile":user.mobile})
                role_list=Get_resource(int(user.role_id))
                return Response({"code":200,'msg':'登陆成功',"token":token,'userid':user.id,"role_list":role_list})
            except:
                return Response({"code":400,'msg':'未找到改手机号，请返回注册'})
        else:
            return Response({"code":400,'msg':'验证码已过期，请重新发送'})

# 注册
class mobile_register(APIView):
    def post(self,request):
        smscode=request.data.get("smscode")
        mobile=request.data.get("mobile")
        value=request.data.get("value")
        if not all([smscode,mobile,value]):
            return Response({"code":400,'msg':'请输入完整的信息进行登录'})
        res=r.get_str(mobile)   #短信验证码解码
        if res:
            res=res.decode()
            if res!=smscode:
                return Response({"code":400,'msg':'手机号验证码错误，请重新输入'})
            res=User.objects.all()
            for i in  res:
                if i.mobile==mobile:
                    return Response({"code":400,'msg':'用户名已存在'})
            try:
                User.objects.get(mobile=mobile)
                return Response({"code": 400, 'msg': '已查到您的手机号，请返回登录'})
            except:
                r.del_str(mobile)
                dada = time.time()
                dada = f"{str(dada)[3:7]}{str(dada)[-6:]}"
                user = User.objects.create(mobile=mobile, name=dada, role_id=int(value))
                token = jj.jwt_encode(data={"id": user.id, "mobile": user.mobile})
                role_list = Get_resource(int(user.role_id))
                return Response(
                    {"code": 200, 'msg': f'注册成功，您的初始账号为{dada}', "token": token, 'userid': user.id,"role_list":role_list})
        else:
            return Response({"code":400,'msg':'验证码已过期，请重新发送'})

# 获取role
class Get_role(APIView):
    def get(self,request):
        ress = r.get_str("role")# 从redis中获取
        if ress:# 先判断redis里面有没有
            # 有了解码返回
            ress=ress.decode()
            return Response({"code": 200, 'msg':eval(ress)})
        # 没有从数据库查询
        res=Role.objects.all()
        # 序列化
        list=[]
        for i in res:
            list.append({
                "id":i.id,
                "name":i.name
            })
        r.set_str("role",str(list))
        return Response({"code":200,'msg':list})


# 第三方登录
# 1（拉起微博第三方接口）
class Wb_url(APIView):
    def get(self,request):
        client_id = "3674019597"
        redirect_uri = "http://127.0.0.1:8000/user/weiboCallback/"
        url = "https://api.weibo.com/oauth2/authorize?client_id=%s&redirect_uri=%s&response_type=code" % (
            client_id, redirect_uri)
        return Response({"code":200,'url':url})

# 2 (从微博获取userid和token)
class Wb_token(APIView):
    def get(self,request):
        code=request.query_params.get("code")
        data = {"client_id": '3674019597', "client_secret": "7ae99bc0d54ead29fc8d1b9fabd78587",
                "grant_type": "authorization_code",
                'redirect_uri': 'http://127.0.0.1:8000/user/weiboCallback/', 'code': code}
        res = requests.post('https://api.weibo.com/oauth2/access_token', data=data)
        # 根据返回结果操作
        # 获取token和uid
        message=json.loads(res.text)
        token=message['access_token']
        uid=message['uid']
        # 查询数据库中是否存在，如果存在就用用户信息生成jwt  token返回
        # try:
        res = Sf_login.objects.get(uid=uid)
        aid=res.userid_id
        res3=User.objects.get(id=int(aid)) # 根据用户id查询当前手机号
        print("查询到了，进行token生成")
        token=jj.jwt_encode(
            data={"data":{"id":res3.id,"mobile":res3.mobile}}
        )# jwt加密生成token
        print("走的有")
        role_list = Get_resource(int(res3.role_id))
        return HttpResponsePermanentRedirect("http://localhost:8080/sf_zhong?token="+token+"&userid="+str(res3.id)+"&role_list="+json.dumps(role_list))#跳转致中专页面
        # except Exception as a:
        #     print("走的没有")
        #     return HttpResponsePermanentRedirect("http://localhost:8080/login1?token="+str(token)+"&uid="+str(uid))#跳转致中专页面

# 3 绑定
class add_sf_login(APIView):
    def post(self,request):
        uid=request.data.get("uid")
        mobile=request.data.get("mobile")
        token=request.data.get("token")
        role_id=request.data.get("roleid")
        if not all([uid,mobile,token]):
            return Response({"code":400,'msg':'字段不完整'})
        if not re.findall(r"1[3-9]\w{9}$", mobile):
            return Response({"code": 400, 'msg': '手机号格式错误'})
        try:
            res=User.objects.get(mobile=mobile)
            Sf_login.objects.create(uid=uid,sf_token=token,sf_type="wb",userid_id=res.id)
            token = jj.jwt_encode(
                data={"data": {"id": res.id, "mobile": res.mobile}}
            )  # jwt加密生成token
            role_list = Get_resource(int(res.role_id))
            return Response({"code":200,'token':token,'userid':res.id,"role_list":role_list})
        except Exception as a:
            dada=time.time()
            dada = f"{str(dada)[3:7]}{str(dada)[-6:]}"
            User.objects.create(mobile=mobile,role_id=int(role_id),name=dada)
            res=User.objects.get(mobile=mobile)
            Sf_login.objects.create(uid=uid, sf_token=token, sf_type="wb", userid_id=res.id)
            role_list = Get_resource(int(res.role_id))
            token = jj.jwt_encode(
                data={"data": {"id": res.id, "mobile": res.mobile}}
            )  # jwt加密生成token
            return Response({"code":200,'token':token,'userid':res.id,"role_list":role_list})

# 需要对用户进行实名注册
class autonym(APIView):
    def get(self,request):
        token = request.headers.get('token')
        if not all([token]):
            return redirect("http://localhost:8080/home")
        else:
            user =jj.jwt_decode(token)
            user=dict(user)
            user=user['data']
            userid=user['id']
            try:
                identity.objects.get(userid_id=userid)
                return redirect("发布标的页面")
            except Exception as a:
                return redirect("绑定页面")


# 七牛云获取token
class imgqny(APIView):
    def get(self,request):
        # 需要填写你的 Access Key 和 Secret Key
        access_key = 'VWKXpfhRZSeT-SMMo4HEJ708LO6pd4rBBToTQv36'
        secret_key = 'CpX7R__itUIcFNH-JQ2uop1Wu-syEoAQvlkhp0SR'
        # 构建鉴权对象
        q = Auth(access_key, secret_key)
        # 要上传的空间
        bucket_name = 'adminctg1'
        # 上传后保存的文件名
        # 生成上传 Token，可以指定过期时间等
        token = q.upload_token(bucket_name)
        return Response({"code":200,'token':token})

# 获取文字识别接口
from zbj.urlis.baidu import bd
class character(APIView):
    def post(self,request):
        "http://rpuhgscze.hb-bkt.clouddn.com/1.jpg"
        data = request.data.get("imgurl")
        # 调取接口进行传参
        res = bd.getmes(data)
        # 给获取到的数据内容赋值
        res0=res[0]['words']
        res1 = res[1]['words']
        # 切片取出前17位
        res3=res0[0:17]
        print(type(res0))
        print(type(res1))
        try:
            # 判断里面是否是数字
            int(res3)
            # 如果是数字就进行赋值，第一个是身份证号码，第二个是用户姓名
            res0 = res[1]['words']
            res1 = res[0]['words']
            return Response({"code": 200, 'msg': res0, 'msg2': res1})
            # 如果不是数字就把赋值内容颠倒，第2个是身份证号码，第1个则是用户姓名
        except:
            res1 = res[1]['words']
            res0 = res[0]['words']
            return Response({"code":200,'msg':res0,'msg2':res1})


# 进行用户绑定接口
class user_identity(APIView):
    def post(self,request):
        name=request.data.get("name")
        code=request.data.get("code")
        s_type=request.data.get("s_type")
        userid=request.data.get("userid")
        if not all([name,code,s_type,userid]):
            return Response({"code":400,'msg':'字段不完整'})







